﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

using System;
using System.Linq;

namespace zijian666.WebApi
{
    /// <summary>
    /// WebApi脚手架扩展方法
    /// </summary>
    public static partial class WebApiExtensions
    {
        /// <summary>
        /// 添加 WebApi支持, 并设置选项
        /// </summary>
        /// <exception cref="ArgumentNullException"></exception>
        public static IMvcBuilder AddWebApiOptions(this IMvcBuilder mvcBuilder, Action<WebApiOptions> action)
        {
            if (mvcBuilder is null)
            {
                throw new ArgumentNullException(nameof(mvcBuilder));
            }
            var option = mvcBuilder.Services.Select(x => x.ImplementationInstance as WebApiOptions).FirstOrDefault(x => x is not null);
            if (option is null)
            {
                option = new WebApiOptions(mvcBuilder);
                mvcBuilder.Services.TryAddSingleton<HttpContextAccessor>();
                mvcBuilder.Services.AddHttpContextAccessor();
            }
            action?.Invoke(option);
            return mvcBuilder;
        }

    }
}
